<?php


namespace app\common\business;


use app\common\model\PatientInfo;
use catchAdmin\cms\model\BaseModel;

use catchAdmin\permissions\model\Users;
use catcher\Code;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use app\common\lib\Redis;
use catcher\exceptions\ValidateFailedException;

class UserCenter
{
    public function getDoctorInfo(array $param)
    {
        try {
            if (!empty($param["ticket"])) {

                // if (Redis::getInstance()->redis->keys("ticket:" . $param["ticket"])) 
                // {
                //     throw new FailedException("无效票据");
                // }

                $ticketData = json_decode(base64_decode(mb_substr($param["ticket"], 64)), true, 512, JSON_THROW_ON_ERROR);

                if (empty($ticketData)) {
                    throw new FailedException("验签失败");
                }
                //根据医生编码获取人员信息
                $doctorInfo = (new Users())->where([["doctor_code", "=", $ticketData["doctor_code"]]])->find();
                if (empty($doctorInfo)) {
                    throw new FailedException("账号不存在", Code::USER_FORBIDDEN);
                }

            } else {
                //根据医生编码获取人员信息
                $doctorInfo = (new Users())->where([["doctor_code", "=", $param["username"]]])->find();
                if (empty($doctorInfo)) {
                    throw new FailedException("密码不正确", Code::USER_FORBIDDEN);
                }
                //校验密码是否正确
                if (!password_verify($param["password"], $doctorInfo["password"])) {
                    throw new FailedException("密码不正确");
                }
            }
            //Redis::getInstance()->redis->setex("ticket:" . $param["ticket"], 600, "OK");
            return $doctorInfo;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }

    }

    public function getUserInfo(array $param): array
    {
        try {

            if (!empty($param["ticket"])) {
                $ticket = $param["ticket"];
                // 输入验证：使用正则表达式验证ticket的合法性
                if (!preg_match('/^[A-Za-z0-9-_=]+$/', $ticket)) {
                    throw new FailedException("非法的ticket格式");
                }
                $ticketData = json_decode(base64_decode(mb_substr($param["ticket"], 64)), true, 512, JSON_THROW_ON_ERROR);

                if (empty($ticketData)) {
                    throw new FailedException("验签失败");
                }

                //根据医生编码获取人员信息
                $patientInfo = (new PatientInfo())->where([["idno", "=", $ticketData["patient_code"]]])->find();

                if (empty($patientInfo)) {
                    //throw new FailedException("账号不存在", Code::USER_FORBIDDEN);
                    //执行建档操作
                    if (!isset($ticketData["patient_code"], $ticketData["mobile"], $ticketData["name"])) {
                        throw new ValidateFailedException("请检查ticket串加密前参数,参数值不完整");
                    }

                    $patientInfo = (new Patient())->filing($ticketData);

                    if (empty($patientInfo)) {
                        throw new FailedException("账号不存在", Code::USER_FORBIDDEN);
                    }
                }
                return $patientInfo->toArray();
            }

        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
        return [];
    }

    /**
     * 生成 ticket
     * @param array $data 条件 患者端patient_code ，医生端doctor_code
     * @return string
     */
    public function generateTicket(array $data): string
    {
        return hash('sha256', time()) . base64_encode(json_encode($data));
    }

}
